package light.head.controller.inv;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.inv.InvBillConfingDAO;
import light.head.dao.inv.InvBusinessDAO;
import light.head.dao.inv.InvCommodityItemDAO;
import light.head.dao.inv.InvDepotDAO;
import light.head.dao.inv.InvInStorageDAO;
import light.head.dao.inv.InvInStorageDetailDAO;
import light.head.dao.inv.InvInStorageItemDAO;
import light.head.dao.inv.InvOutStorageDAO;
import light.head.dao.inv.InvOutStorageDetailDAO;
import light.head.dao.inv.InvOutStorageItemDAO;
import light.head.dao.inv.InvStorageDAO;
import light.head.dao.inv.InvStorageDetailDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.ExcelUtils;
import light.head.model.inv.InvDepot;
import light.head.model.inv.InvInStorage;
import light.head.model.inv.InvInStorageDetail;
import light.head.model.inv.InvInStorageItem;
import light.head.model.inv.InvOutStorage;
import light.head.model.inv.InvOutStorageDetail;
import light.head.model.inv.InvOutStorageItem;
import light.head.model.inv.InvStorage;
import light.head.model.inv.InvStorageDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(Url.C_INVSTORAGE)
public class InvStorageController extends SupporterController{
	
	private InvStorageDAO isDAO;
	private InvStorageDetailDAO detailDAO;
	private InvCommodityItemDAO iciDAO;
	private InvDepotDAO idDAO;
	private InvInStorageDAO iisDAO;
	private InvInStorageItemDAO iisiDAO;
	private InvInStorageDetailDAO iisdDAO;
	private InvOutStorageDAO iosDAO;
	private InvOutStorageItemDAO iosiDAO;
	private InvOutStorageDetailDAO iosdDAO;
	private InvBusinessDAO ibDAO;
	private InvBillConfingDAO ibcfDAO;
	private OrganDAO organDAO;

	private final static String fileName = "库存导出.xls";
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.INVSTORAGE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query (HttpServletRequest request, HttpServletResponse response) throws Exception{
		PageBean pb = createPageBean(request);
		Map<String,String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.DNAME,Parm.CNAME,Parm.ON);
		if (isDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS) {
			InvStorage is =null;
			for (Object o : pb.getResultList()) {
				is = (InvStorage) o;
				is.setDetailList(detailDAO.findByIsc(is.getCode()));
			}
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.INVSTORAGE_LIST);
	}
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvStorage de = isDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(true);
		if (isDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvStorage de = isDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(false);
		if (isDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	@RequestMapping(value = Url.IN)
	public ModelAndView in(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvStorage is = isDAO.get(Integer.parseInt(code));
			List<InvStorageDetail> item = detailDAO.findByIsc(is.getCode());
			is.setDetailList(item);
			request.setAttribute(Parm.INVSTORAGE, is);
		}
		List<InvDepot> typeList = idDAO.findAll(organDAO.getSonCodeList(cu_organCode(request)));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			for (InvDepot type : typeList){
				result.append("{");
				result.append("\"dname\":\"" + type.getName() +"\",");
				result.append("\"dc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		}
		return new ModelAndView(Url.INVSTORAGE_IN);
	}
	
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvStorage is = isDAO.get(Integer.parseInt(code));
			List<InvStorageDetail> detailList = detailDAO.findByIsc(is.getCode());
			is.setDetailList(detailList);
			request.setAttribute(Parm.INVSTORAGE, is);
		} 
		return new ModelAndView(Url.INVSTORAGE_DETAIL);
	}
	//入库
	@Transactional
	@RequestMapping(value = Url.INSTOCK)
	public void InvIn(InvInStorage iis, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		List<InvInStorageItem> itemList = iis.getItemList();			// 提交上来的数组
		
		iis.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_THREE));
		iis.setCt(new Date());
		iis.setDeleted(false);
		iis.setCu(cu_code(request));
		iis.setOc(cu_organCode(request));
		result = iisDAO.add(iis); 	// 入库记录
		// 保存
		for (InvInStorageItem item : itemList) {
			if (item != null && item.getCc() != null && item.getNumber() != null){
				Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
				List<InvDepot> isc = idDAO.findByNameOc(item.getDname(), organDAO.getSonCodeList(oc));
				if (isc == null || isc.size() == 0)  {
					InvDepot ibt = new InvDepot();
					ibt.setName(item.getDname());
					ibt.setCt(new Date());
					ibt.setDeleted(false);
					ibt.setOc(cu_organCode(request));
					ibt.setCu(cu_code(request));
					idDAO.add(ibt);
					item.setDc(ibt.getCode());
				}
				// 保存入库明细
				item.setIisc(iis.getCode());
				item.setDeleted(false);
				result = iisiDAO.add(item);
				// 保存库存
				
				List<InvStorage> dbList = isDAO.findByCcDc(item.getCc(),item.getDc(), organDAO.getSonCodeList(cu_organCode(request)));
				String serial = detailDAO.findByCcOc(item.getCc(), organDAO.getSonCodeList(oc));
				if (null != dbList && dbList.size() > 0) {
					dbList.get(0).setCount(dbList.get(0).getCount() + item.getNumber());
					dbList.get(0).setRemark(item.getRemark());
					result = isDAO.upd(dbList.get(0));
					
					if (item.getSnc().intValue() == 3 || (item.getSnc().intValue() == 2 && serial == null)) {
						for(InvInStorageDetail iisd : item.getDetailList()){
							if (iisd != null && iisd.getSerial() != null){
								iisd.setDeleted(false);
								iisd.setIisic(item.getCode());
								result = iisdDAO.add(iisd);									//	保存入库串号
								if (result == RESULT.SUCCESS){
									InvStorageDetail isd = new InvStorageDetail();
									isd.setDeleted(false);
									isd.setIsc(dbList.get(0).getCode());
									isd.setSerial(iisd.getSerial());
									result = detailDAO.add(isd);								// 保存库存串号
								}
							}
						}
					} 
					//如果snc是2并且已经有序列号的 直接保存入库串号
					if (item.getSnc().intValue() == 2 && serial != null) {
						InvInStorageDetail iisd = new InvInStorageDetail();
						iisd.setDeleted(false);
						iisd.setIisic(item.getCode());
						iisd.setSerial(serial);
						result = iisdDAO.add(iisd);
					}
				} else {
					InvStorage sto = new InvStorage();
					sto.setCc(item.getCc());
					sto.setCname(item.getCname());
					sto.setDc(item.getDc());
					sto.setOc(iis.getOc());
					sto.setDeleted(false);
					sto.setSnc(item.getSnc());
					sto.setRemark(item.getRemark());
					sto.setCount(item.getNumber());
					result = isDAO.add(sto);
					if (item.getSnc().intValue() == 3 || (item.getSnc().intValue() == 2 && serial == null)) {
						for(InvInStorageDetail iisd : item.getDetailList()){
							if (iisd != null && iisd.getSerial() != null){
								iisd.setDeleted(false);
								iisd.setIisic(item.getCode());
								result = iisdDAO.add(iisd);									//	保存入库串号
								if (result == RESULT.SUCCESS){
									InvStorageDetail isd = new InvStorageDetail();	
									isd.setDeleted(false);
									isd.setIsc(sto.getCode());
									isd.setSerial(iisd.getSerial());
									result = detailDAO.add(isd);								// 保存库存串号
								}
								
							}
						}
					}
					if (item.getSnc().intValue() == 2 && serial != null) {
						InvInStorageDetail iisd = new InvInStorageDetail();
						iisd.setDeleted(false);
						iisd.setIisic(item.getCode());
						iisd.setSerial(serial);
						result = iisdDAO.add(iisd);
					}
				}
			}
		}
		print(response, Msg.SUCCESS);
	}
	
	/**
	 * 查询商品
	 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVSTORAGE_AID_INIT);
	}
	
	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == iciDAO.findByMap(oc, map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVSTORAGE_AID_LIST);
	}
	/**
	 * 查询仓库
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVSTORAGE_AID_INIT1);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		if (RESULT.SUCCESS == idDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVSTORAGE_AID_LIST1);
	}
	/**
	 * 查询供应商
	 */
	@RequestMapping(Url.AID_INIT_2)
	public ModelAndView aidInit2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVSTORAGE_AID_INIT2);
	}
	
	@RequestMapping(Url.AID_LIST_2)
	public ModelAndView aidList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == ibDAO.findByMap(oc, map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVSTORAGE_AID_LIST2);
	}
	@RequestMapping(value = Url.VERIFY)
	public void serial(HttpServletRequest request, HttpServletResponse response){
		String serial = request.getParameter("serial");
		List<InvStorageDetail> detailList = detailDAO.findBySerial(serial);
		if (detailList != null && detailList.size() > 0) {
			print(response, Msg.ERROR);
		} else {
			print(response, Msg.SUCCESS);
		}
	}
		
		
		
		
		
	@RequestMapping(value = Url.OUT)
	public ModelAndView out(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvStorage is = isDAO.get(Integer.parseInt(code));
			List<InvStorageDetail> item = detailDAO.findByIsc(is.getCode());
			is.setDetailList(item);
			request.setAttribute(Parm.INVSTORAGE, is);
		} 
		return new ModelAndView(Url.INVSTORAGE_OUT);
	}
	
	//出库
	@Transactional
	@RequestMapping(value = Url.OUTSTOCK)
	public void InvOut(InvOutStorage ios, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		List<InvOutStorageItem> itemList = ios.getItemList();			// 提交上来的数组
		ios.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_FOUR));
		ios.setCt(new Date());
		ios.setDeleted(false);
		ios.setType(Sys.B_ONE);
		ios.setCu(cu_code(request));
		ios.setOc(cu_organCode(request));
		result = iosDAO.add(ios); 	// 出库记录
		// 保存
		for (InvOutStorageItem item : itemList) {
			if (item != null && item.getCc() != null && item.getNumber() != null){
				// 保存出库明细
				item.setIosc(ios.getCode());
				item.setDeleted(false);
				result = iosiDAO.add(item);
				// 保存出库记录
				Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
				String serial = detailDAO.findByCcOc(item.getCc(), organDAO.getSonCodeList(oc));
				if (item.getSnc().intValue() == 2 && serial != null) {
					InvOutStorageDetail iosd = new InvOutStorageDetail();
					iosd.setDeleted(false);
					iosd.setIosic(item.getCode());
					iosd.setSerial(serial);
					result = iosdDAO.add(iosd);
				}
				List<InvStorage> dbList = isDAO.findByCcDc(item.getCc(),item.getDc(), organDAO.getSonCodeList(cu_organCode(request)));
				
				if (null != dbList && dbList.size() > 0) {
					if (dbList.get(0).getCount().intValue() <= 0 ) {
						print(response, Msg.EXISTS);
						return;
					}if (dbList.get(0).getCount().intValue() < item.getNumber()) {
						print(response, Msg.NOT_FIND);
						return;
					}
					dbList.get(0).setCount(dbList.get(0).getCount() - item.getNumber());
					dbList.get(0).setRemark(item.getRemark());
					result = isDAO.upd(dbList.get(0));
					if (item.getSnc().intValue() == 3 || (item.getSnc().intValue() == 2 && serial == null)) {
						for(InvOutStorageDetail iisd : item.getDetailList()){
							if (iisd != null && iisd.getSerial() != null) {
								iisd.setDeleted(false);
								iisd.setIosic(item.getCode());
								result = iosdDAO.add(iisd);									//	保存出库串号
								if (result == RESULT.SUCCESS){
									List<InvStorageDetail> isdList = detailDAO.findByOc(iisd.getSerial(), organDAO.getSonCodeList(oc));
									if (null != isdList && isdList.size() != 0){
										result = detailDAO.del(isdList.get(0));	
									}							// 删除库存串号
								}
							}
						}
					}
				} else {
					print(response, Msg.ERROR);
					return;
				}
			}	
		}
		print(response, Msg.SUCCESS);
	}	
		
	/**
	 * 查询库存商品
	 */
	@RequestMapping(Url.S_INIT)
	public ModelAndView sInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVSTORAGE_S_INIT);
	}
	
	@RequestMapping(Url.S_LIST)
	public ModelAndView sList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		if (RESULT.SUCCESS == isDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVSTORAGE_S_LIST);
	}	
		
	@RequestMapping(value = Url.VERIFY2)
	public void serial2(HttpServletRequest request, HttpServletResponse response){
		String serial = request.getParameter("serial");
		String cc = request.getParameter("cc");
		String dc = request.getParameter("dc");
		List<InvStorageDetail> detailList = detailDAO.findBySerialCcDc(serial,Integer.parseInt(cc),Integer.parseInt(dc));
		if (detailList != null && detailList.size() > 0) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}	
		
	@RequestMapping(value = Url.CHECK)
	public void check(HttpServletRequest request, HttpServletResponse response){
		String cc = request.getParameter("cc");
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		String serial = detailDAO.findByCcOc(Integer.parseInt(cc), organDAO.getSonCodeList(oc));
		print(response, serial);
	}	
		
	// 库存导出
	@RequestMapping(Url.EXCEL_EXPORT)
	public void exclExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.DNAME,Parm.CNAME,Parm.ON);
		map.put(Parm.CU, cu_code(request).toString());
		map.put(Parm.OC, cu_organCode(request).toString());
		List<InvStorage> list = isDAO.findByMap1(organDAO.getSonCodeList(cu_organCode(request)), map);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
		ExcelUtils.writeExcel(list, "库存", response.getOutputStream(), null, null);
	}
	
	
	@Autowired
	public void setIsDAO(InvStorageDAO isDAO) {
		this.isDAO = isDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setDetailDAO(InvStorageDetailDAO detailDAO) {
		this.detailDAO = detailDAO;
	}
	@Autowired
	public void setIisDAO(InvInStorageDAO iisDAO) {
		this.iisDAO = iisDAO;
	}
	@Autowired
	public void setIisiDAO(InvInStorageItemDAO iisiDAO) {
		this.iisiDAO = iisiDAO;
	}
	@Autowired
	public void setIosDAO(InvOutStorageDAO iosDAO) {
		this.iosDAO = iosDAO;
	}
	@Autowired
	public void setIosiDAO(InvOutStorageItemDAO iosiDAO) {
		this.iosiDAO = iosiDAO;
	}
	@Autowired
	public void setIciDAO(InvCommodityItemDAO iciDAO) {
		this.iciDAO = iciDAO;
	}
	@Autowired
	public void setIdDAO(InvDepotDAO idDAO) {
		this.idDAO = idDAO;
	}
	@Autowired
	public void setIisdDAO(InvInStorageDetailDAO iisdDAO) {
		this.iisdDAO = iisdDAO;
	}
	@Autowired
	public void setIbcfDAO(InvBillConfingDAO ibcfDAO) {
		this.ibcfDAO = ibcfDAO;
	}
	@Autowired
	public void setIbDAO(InvBusinessDAO ibDAO) {
		this.ibDAO = ibDAO;
	}
	@Autowired
	public void setIosdDAO(InvOutStorageDetailDAO iosdDAO) {
		this.iosdDAO = iosdDAO;
	}
	
}
